package com.ws;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.websocket.Session;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 会话管理
 * 存储每个客户端连接的会话，提供获取会话信息的方法
 */
@Component
public class SessionManager {

    /**
     * 每个用户在登录后都会开启一个会话
     */
    private static final ConcurrentHashMap<Long, Session> USER_SESSION = new ConcurrentHashMap<>();

    public Session getSession(Long userId) {
        return USER_SESSION.get(userId);
    }

    /**
     * 是否连接
     *
     * @param userId
     * @return
     */
    public boolean isConnection(Long userId) {
        return USER_SESSION.containsKey(userId);
    }

    /**
     * 加入会话
     *
     * @param userId
     * @param session
     */
    public void joinSession(Long userId, Session session) {
        USER_SESSION.putIfAbsent(userId, session);
    }

    /**
     * 断开会话
     *
     * @param userId
     */
    public void leaveSession(Long userId) {
        if (userId != null) {
            USER_SESSION.remove(userId);
        }
    }

    /**
     * 根据用户id批量发送消息
     *
     * @param message
     * @param userIds
     */
    //TODO 这么搞，在线人数没了
    //TODO 在消息中添加发送者的基本信息，昵称，头像
    public void sendBatchMessage(String message, ArrayList<Long> userIds, Long teamId) {
        if (CollectionUtils.isEmpty(userIds)) {
            return;
        }
        for (Long userId : userIds) {
            sendMessage(message, userId, teamId);
        }
    }

    /**
     * 私聊
     *
     * @param message
     * @param senderId
     * @param receiverId
     * @return
     */
    public void privateChat(String message, Long senderId, Long receiverId) {
        sendMessage(message, senderId, receiverId);
        sendMessage(message, receiverId, senderId);
    }


    /**
     * 给单个用户发送消息,带数据同步
     *
     * @param message
     * @param userId
     * @return
     */
    public void sendMessage(String message, Long userId, Long receiverId) {
        Session session = USER_SESSION.get(userId);
        syncMessage(session, receiverId);
        if (session != null) {
            try {
                session.getBasicRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void sendMessage(String message, Long receiverId) {
        Session session = USER_SESSION.get(receiverId);
        if (session != null) {
            try {
                session.getBasicRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void syncMessage(Session session, Long chatId) {
        if (WebSocketSync.hasSync(session)) {
            WebSocketSync.addSync(session, chatId);
        }
    }

}
